package com.xzakota.minesweeper.util;

import java.io.*;

/**
 * 文件处理工具类
 *
 * @author Xzakota
 */
public class FileUtils {
    public static String readFile(String filePath) {
        return readFile(new File(filePath));
    }

    public static String readFile(File file) {
        try {
            return new String(readStream(new FileInputStream(file)));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] readStream(InputStream inStream) {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        readStream(inStream, outSteam);
        return outSteam.toByteArray();
    }

    public static void readStream(InputStream inStream, OutputStream outStream) {
        try (outStream) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean writeFileFromString(String path, String content, Boolean append) {
        return writeFileFromString(new File(path), content, append);
    }

    public static boolean writeFileFromString(File file, String content, Boolean append) {
        if (file == null || content == null) {
            return false;
        }

        createFileIfNotExist(file);

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, append))) {
            writer.write(content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return true;
    }

    public static boolean createDirIfNotExist(File dir) {
        if (dir != null) {
            if (!dir.exists()) {
                return dir.mkdirs();
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    public static boolean createFileIfNotExist(File file) {
        if (file != null) {
            if (!createDirIfNotExist(file.getParentFile())) {
                return false;
            }

            if (!file.exists()) {
                try {
                    return file.createNewFile();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
}
